<template>
  <el-select v-model="id" class="form-item-flex-between" clearable :disabled="disabled" @change="handleChange">
    <el-option v-for="(item, index) in typeList" :key="index" :value="item.id" :label="item.name" />
  </el-select>
</template>
<script>
import { getType } from "@/api/configCenter/productList";
export default {
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
    value: {
      type: [String, Number],
      default: "",
    },
    name: {
      type: [String, Number],
      default: "",
    },
    productId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      id: "",
      typeList: [],
    };
  },
  watch: {
    value: {
      handler(val) {
        this.handleData();
      },
      deep: true,
      immediate: true,
    },
    productId: {
      handler(val) {
        if (val) {
          this.getType(val);
        }
        console.log(val, "传入的获取业务类型的产品id");
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    handleChange(e) {
      const data = (this.typeList || []).filter(item => { return item.id === this.id; })[0] || {};
      this.$emit("change", data);
    },
    getType(id) {
      getType(id).then(res => {
        if (res.statusCode === 600 && res.data) {
          this.typeList = [...res.data];
          if (this.value) {
            this.handleData();
          }
        }
      });
    },
    handleData() {
      const index = this.typeList.findIndex((item) => {
        return this.value === item.id;
      });
      if (index === -1) {
        this.id = this.name || "";
        // this.$emit("change", {});
      } else {
        this.id = this.value;
        const data = (this.typeList || []).filter(item => { return item.id === this.id; })[0] || {};
        this.$emit("change", data);
      }
    },
    clear() {
      this.id = "";
    },
  },
};
</script>
